<template>
  <div class="pet-care-manage-container">
    <h1 class="page-title">🧴 宠物护理管理</h1>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="宠物名称">
          <el-input v-model="searchForm.petName" placeholder="请输入宠物名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="护理类型">
          <el-select v-model="searchForm.careType" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="喂食" :value="1"></el-option>
            <el-option label="洗澡" :value="2"></el-option>
            <el-option label="美容" :value="3"></el-option>
            <el-option label="训练" :value="4"></el-option>
            <el-option label="其他" :value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工姓名">
          <el-input v-model="searchForm.employeeName" placeholder="请输入员工姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="护理状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="全部" :value="null"></el-option>
            <el-option label="已完成" :value="1"></el-option>
            <el-option label="进行中" :value="2"></el-option>
            <el-option label="已取消" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="护理时长(分钟)">
          <el-input-number v-model="searchForm.minDuration" :min="0" placeholder="最短" controls-position="right" style="width: 130px;"></el-input-number>
          <span style="margin: 0 10px;">-</span>
          <el-input-number v-model="searchForm.maxDuration" :min="0" placeholder="最长" controls-position="right" style="width: 130px;"></el-input-number>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          <el-button type="success" icon="el-icon-plus" @click="handleAdd">新增护理记录</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 护理记录列表 -->
    <el-card style="margin-top: 20px;">
      <el-table :data="careList" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="petName" label="宠物名称"></el-table-column>
        <el-table-column prop="careType" label="护理类型" width="120">
          <template slot-scope="scope">
            <el-tag :type="getCareTypeTag(scope.row.careType)">{{ scope.row.careTypeName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="staffName" label="护理人员"></el-table-column>
        <el-table-column prop="careDate" label="护理日期" width="120"></el-table-column>
        <el-table-column prop="careTime" label="护理时间" width="120">
          <template slot-scope="scope">
            {{ formatCareTime(scope.row.careTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" type="primary" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
              <el-button size="mini" type="warning" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog title="护理记录详情" :visible.sync="viewDialogVisible" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="宠物名称">{{ viewCareData.petName }}</el-descriptions-item>
        <el-descriptions-item label="护理类型">
          <el-tag :type="getCareTypeTag(viewCareData.careType)">{{ viewCareData.careTypeName }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="护理人员">{{ viewCareData.staffName }}</el-descriptions-item>
        <el-descriptions-item label="护理日期">{{ viewCareData.careDate }}</el-descriptions-item>
        <el-descriptions-item label="护理时间">{{ formatCareTime(viewCareData.careTime) }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(viewCareData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="护理描述" :span="2">{{ viewCareData.description || '无' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ viewCareData.remark || viewCareData.notes || '无' }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer">
        <el-button type="primary" @click="viewDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="careForm" :rules="careRules" ref="careForm" label-width="100px">
        <el-form-item label="选择宠物" prop="petId">
          <el-select v-model="careForm.petId" placeholder="请选择宠物" filterable style="width: 100%">
            <el-option v-for="pet in petList" :key="pet.id" :label="pet.name" :value="pet.id">
              <span>{{ pet.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ pet.breed }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="护理类型" prop="careType">
          <el-select v-model="careForm.careType" placeholder="请选择护理类型" style="width: 100%">
            <el-option label="喂食" value="1"></el-option>
            <el-option label="洗澡" value="2"></el-option>
            <el-option label="美容" value="3"></el-option>
            <el-option label="训练" value="4"></el-option>
            <el-option label="其他" value="5"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="护理人员" prop="staffId">
          <el-select v-model="careForm.staffId" placeholder="请选择护理人员" style="width: 100%">
            <el-option v-for="staff in staffList" :key="staff.id" :label="staff.name" :value="staff.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="护理日期" prop="careDate">
          <el-date-picker
            v-model="careForm.careDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="护理时间" prop="careTime">
          <el-time-picker
            v-model="careForm.careTime"
            placeholder="选择时间"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            style="width: 100%">
          </el-time-picker>
        </el-form-item>

        <el-form-item label="备注">
          <el-input type="textarea" v-model="careForm.remark"
                    :rows="3" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAdminCareList } from '@/api/care'
import careApi from '@/api/care'
import petApi from '@/api/pet'
import staffApi from '@/api/staff'

export default {
  name: 'PetCareManage',
  data () {
    return {
      searchForm: {
        petName: '',
        careType: null,
        employeeName: '',
        status: null,
        minDuration: null,
        maxDuration: null,
        dateRange: null
      },
      careList: [],
      petList: [],
      staffList: [],
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      viewDialogVisible: false,
      viewCareData: {},
      dialogTitle: '新增护理记录',
      careForm: {
        petId: null,
        careType: '1',
        staffId: null,
        careDate: '',
        careTime: '',
        remark: ''
      },
      careRules: {
        petId: [{ required: true, message: '请选择宠物', trigger: 'change' }],
        careType: [{ required: true, message: '请选择护理类型', trigger: 'change' }],
        staffId: [{ required: true, message: '请选择护理人员', trigger: 'change' }],
        careDate: [{ required: true, message: '请选择护理日期', trigger: 'change' }],
        careTime: [{ required: true, message: '请选择护理时间', trigger: 'change' }]
      }
    }
  },
  created () {
    this.loadCareList()
    this.loadPetList()
    this.loadStaffList()
  },
  methods: {
    async loadCareList () {
      this.loading = true
      try {
        // 构建查询参数
        const params = {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }
        
        // 添加筛选条件
        if (this.searchForm.petName) {
          params.petName = this.searchForm.petName
        }
        if (this.searchForm.careType !== null && this.searchForm.careType !== '') {
          params.careType = this.searchForm.careType
        }
        if (this.searchForm.employeeName) {
          params.employeeName = this.searchForm.employeeName
        }
        // 护理状态
        if (this.searchForm.status !== null && this.searchForm.status !== '') {
          params.status = this.searchForm.status
        }
        // 护理时长范围
        if (this.searchForm.minDuration !== null && this.searchForm.minDuration !== '') {
          params.minDuration = this.searchForm.minDuration
        }
        if (this.searchForm.maxDuration !== null && this.searchForm.maxDuration !== '') {
          params.maxDuration = this.searchForm.maxDuration
        }
        // 日期范围
        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
          params.startDate = this.searchForm.dateRange[0]
          params.endDate = this.searchForm.dateRange[1]
        }
        
        console.log('护理查询参数:', params)
        const res = await getAdminCareList(params)
        console.log('护理返回数据:', res)
        
        // 处理响应数据
        const data = (res.data && res.data.records) || (res.data && res.data.list) || res.data || []
        this.careList = data.map(item => ({
          id: item.id,
          petName: item.petName || item.pet_name || '未知',
          careType: item.careType || item.care_type,
          careTypeName: item.careTypeName || this.getCareTypeName(item.careType || item.care_type),
          employeeName: item.employeeName || item.employee_name || item.staffName || '未知',
          careDate: item.careDate || item.care_date || '',
          careTime: item.careTime || item.care_time || '',
          duration: item.duration || 0,
          remark: item.remark || item.remark_text || '',
          status: item.status || 1,
          statusName: item.statusName || this.getStatusName(item.status)
        }))
        
        // 更新分页信息
        this.pagination.total = (res.data && res.data.total) || data.length || 0
      } catch (error) {
        console.error('加载失败:', error)
        this.$message.error('加载失败：' + (error.message || '未知错误'))
      } finally {
        this.loading = false
      }
    },
    getCareTypeName (type) {
      const typeMap = {
        1: '喂食',
        2: '洗澡',
        3: '美容',
        4: '训练',
        5: '其他'
      }
      return typeMap[type] || '未知'
    },
    getStatusName (status) {
      const statusMap = {
        1: '已完成',
        2: '进行中',
        3: '已取消'
      }
      return statusMap[status] || '未知'
    },
    async loadPetList () {
      try {
        const res = await petApi.getPetList({ page: 1, size: 100 })
        this.petList = (res.data || []).map(pet => ({
          id: pet.id,
          name: pet.name || pet.pet_name || pet.petName,
          breed: pet.breed
        }))
      } catch (error) {
        console.error('加载宠物列表失败', error)
      }
    },
    async loadStaffList () {
      try {
        const res = await staffApi.getStaffList({ page: 1, size: 100 })
        this.staffList = (res.data || []).map(staff => ({
          id: staff.id || staff.employee_id || staff.employeeId,
          name: staff.name || staff.employee_name || staff.employeeName || staff.staffName
        }))
      } catch (error) {
        console.error('加载员工列表失败', error)
      }
    },
    handleSearch () {
      this.pagination.currentPage = 1
      this.loadCareList()
    },
    handleReset () {
      this.searchForm = {
        petName: '',
        careType: null,
        employeeName: '',
        status: null,
        minDuration: null,
        maxDuration: null,
        dateRange: null
      }
      this.pagination.currentPage = 1
      this.loadCareList()
    },
    handleAdd () {
      this.dialogTitle = '新增护理记录'
      this.careForm = {
        petId: null,
        careType: '1',
        staffId: null,
        careDate: '',
        careTime: '',
        remark: ''
      }
      this.dialogVisible = true
    },
    async handleView (row) {
      try {
        const res = await careApi.getCareDetail(row.id)
        this.viewCareData = res.data || row
        this.viewDialogVisible = true
      } catch (error) {
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    async handleEdit (row) {
      try {
        const res = await careApi.getCareDetail(row.id)
        this.dialogTitle = '编辑护理记录'
        const data = res.data || {}
        
        this.careForm = {
          id: data.id,
          petId: data.petId,
          careType: String(data.careType || '1'),
          staffId: data.employeeId,
          careDate: data.careDate,
          careTime: data.careTime || '',
          remark: data.remark || ''
        }
        this.dialogVisible = true
      } catch (error) {
        console.error('加载详情失败:', error)
        this.$message.error('加载详情失败：' + (error.message || '未知错误'))
      }
    },
    handleDelete (row) {
      this.$confirm(`确认删除该护理记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await careApi.deleteCare(row.id)
          this.$message.success('删除成功')
          this.loadCareList()
        } catch (error) {
          this.$message.error('删除失败：' + (error.message || '未知错误'))
        }
      })
    },
    handleSubmit () {
      this.$refs.careForm.validate(async (valid) => {
        if (valid) {
          try {
            const submitData = {
              ...this.careForm,
              careType: parseInt(this.careForm.careType)
            }
            
            if (this.careForm.id) {
              await careApi.updateCare(this.careForm.id, submitData)
            } else {
              await careApi.addCare(submitData)
            }
            this.$message.success('操作成功')
            this.dialogVisible = false
            this.loadCareList()
          } catch (error) {
            this.$message.error('操作失败：' + (error.message || '未知错误'))
          }
        }
      })
    },
    formatDate (datetime) {
      if (!datetime) return '-'
      return datetime.split('T')[0].split(' ')[0]
    },
    formatCareTime (time) {
      if (!time) return '-'
      const parts = time.split(':')
      const hours = parseInt(parts[0]) || 0
      const minutes = parseInt(parts[1]) || 0
      const seconds = parseInt(parts[2]) || 0
      return `${hours}h ${minutes}min ${seconds}s`
    },
    getCareTypeTag (type) {
      const typeMap = {
        1: 'primary',
        2: 'success',
        3: 'warning',
        4: 'info',
        5: ''
      }
      return typeMap[type] || 'info'
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.loadCareList()
    },
    handleCurrentChange (val) {
      this.pagination.currentPage = val
      this.loadCareList()
    }
  }
}
</script>

<style scoped>
.pet-care-manage-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 24px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}
</style>
